package tiandang.core.service;

import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.RefundRequest;
import com.lly835.bestpay.model.RefundResponse;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tiandang.core.model.OrderInfo;
import tiandang.core.utils.AESUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class RefundNotifyService {

  private final Logger log = LoggerFactory.getLogger(this.getClass());

  @Autowired
  private OrderService orderService;

  @Autowired
  private BestPayServiceImpl bestPayService;

  public RefundResponse create(OrderInfo order) {
    RefundRequest request = new RefundRequest();
    request.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);
    request.setOrderId(order.getId());
    request.setOrderAmount(order.getOrderAmount().doubleValue());
    RefundResponse refundResponse = bestPayService.refund(request);
    return refundResponse;
  }

  public void parseRefundNotifyAndResponse(HttpServletRequest request, HttpServletResponse response) {
    log.info("退款  微信回调接口方法 start");
    String inputLine = "";
    String notityXml = "";
    try {
      while ((inputLine = request.getReader().readLine()) != null) {
        notityXml += inputLine;
      }
      //关闭流
      request.getReader().close();
      log.info("退款  微信回调内容信息：" + notityXml);
      //解析成Map
      Map<String, String> map = doXMLParse(notityXml);
      //判断 退款是否成功
      if ("SUCCESS".equals(map.get("return_code"))) {
        log.info("退款  微信回调返回是否退款成功：是");
        //获得 返回的商户订单号
        String passMap = AESUtil.decryptData(map.get("req_info"));
        //拿到解密信息
        map = doXMLParse(passMap);
        //拿到解密后的订单号
        String outTradeNo = map.get("out_trade_no");
        log.info("退款  微信回调返回商户订单号：" + outTradeNo);
        //退款成功 修改订单状态 通知微信成功回调
        OrderInfo order = orderService.getOrderById(outTradeNo);
        if (order.getOrderStatus() != 4) {
          orderService.updateOrderStatus(outTradeNo, 4);
          orderService.refund(outTradeNo);
        }

      }

      //给微信服务器返回 成功标示 否则会一直询问 咱们服务器 是否回调成功
      PrintWriter writer = response.getWriter();
      //封装 返回值
      StringBuffer buffer = new StringBuffer();
      buffer.append("<xml>");
      buffer.append("<return_code><![CDATA[SUCCESS]]></return_code>");
      buffer.append("<return_msg><![CDATA[OK]]></return_msg>");
      buffer.append("</xml>");
      //返回
      writer.print(buffer.toString());
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private Map<String, String> doXMLParse(String strxml) throws Exception {
    if (null == strxml || "".equals(strxml)) {
      return null;
    }

    Map<String, String> m = new HashMap<String, String>();
    InputStream in = String2Inputstream(strxml);
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(in);
    Element root = doc.getRootElement();
    List list = root.getChildren();
    Iterator it = list.iterator();
    while (it.hasNext()) {
      Element e = (Element) it.next();
      String k = e.getName();
      String v = "";
      List children = e.getChildren();
      if (children.isEmpty()) {
        v = e.getTextNormalize();
      } else {
        v = getChildrenText(children);
      }

      m.put(k, v);
    }

    //关闭流
    in.close();

    return m;
  }

  private InputStream String2Inputstream(String str) {
    return new ByteArrayInputStream(str.getBytes());
  }

  /**
   * 获取子结点的xml
   *
   * @param children
   * @return String
   */
  @SuppressWarnings("rawtypes")
  private static String getChildrenText(List children) {
    StringBuffer sb = new StringBuffer();
    if (!children.isEmpty()) {
      Iterator it = children.iterator();
      while (it.hasNext()) {
        Element e = (Element) it.next();
        String name = e.getName();
        String value = e.getTextNormalize();
        List list = e.getChildren();
        sb.append("<" + name + ">");
        if (!list.isEmpty()) {
          sb.append(getChildrenText(list));
        }
        sb.append(value);
        sb.append("</" + name + ">");
      }
    }

    return sb.toString();
  }
}
